package com.maimang.platform.dsp.service.impl;

import com.maimang.platform.common.utils.DateUtils;
import com.maimang.platform.dsp.entity.AdvertiserIds;
import com.maimang.platform.dsp.mapper.AdvertiserIdsMapper;
import com.maimang.platform.dsp.service.*;
import com.maimang.platform.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.concurrent.Executors;

/**
 * @author Rocky
 * @version 1.0.0
 * @classname DataSyncServiceImpl
 * @description <br>数据同步服务service实现</br>
 * @date 2019-11-27 14:47
 * @email jintaozhao@qq.com
 */
@Service
public class DataSyncServiceImpl implements DataSyncService {

	@Autowired
	private AdvertiserIdsMapper advertiserIdsMapper;

	@Autowired
	private AdvertiserService advertiserService;

	@Autowired
	private BudgetService budgetService;

	@Autowired
	private QualificationService qualificationService;

	@Autowired
	private DeliverService deliverService;

	@Autowired
	private AdService adService;

	@Autowired
	private AdDataService adDataService;

	@Autowired
	private CampaignService campaignService;

	@Autowired
	private CampaignDataService campaignDataService;

	@Autowired
	private FundService fundService;

	@Autowired
	private FundDailyService fundDailyService;

	/**
	 * 同步代理商下属所有广告主的广告组、广告计划、及其相关数据等
	 *
	 * @param advertiserId 代理商广告主id
	 * @param days 天数
	 * @throws Exception
	 */
	@Override
	public void syncData(String advertiserId, int days) throws Exception {
		AdvertiserIds ids = new AdvertiserIds();
		ids.setPId(Long.valueOf(advertiserId));
		List<AdvertiserIds> idsList = advertiserIdsMapper.selectAdvertiserIdsList(ids);
		String today = DateUtils.getToday();
		String startDate = DateUtils.getBeforeDayString(today, days);

		double total = idsList.size();

		int pageSize = 2000;
		double totalPage = Math.ceil(total / pageSize);
		for (int i = 0; i < totalPage; i++) {
			int beginIndex = i * pageSize;
			int endIndex = (int) Math.min((i + 1) * pageSize, total);

			Executors.newFixedThreadPool(20).execute(() -> {
				List<AdvertiserIds> advertiserIdsList = idsList.subList(beginIndex, endIndex);

				for (int j = 0; j < advertiserIdsList.size(); j++) {
					AdvertiserIds advertiserIds = advertiserIdsList.get(j);
					int curPage = 1, curPageSize = 20;

					try {
						// 同步广告组
						campaignService.getCampagin(advertiserIds.getId(), curPage, curPageSize);
						// 同步广告计划
						adService.getAd(advertiserIds.getId(), curPage, curPageSize);
						// 同步广告组数据
						campaignDataService.syncCampaignData(advertiserIds.getId(), startDate, today);
						// 同步广告计划数据
						adDataService.syncAdData(advertiserIds.getId(), startDate, today);
						// 同步账户余额数据
						fundService.syncFundById(advertiserIds.getId());
						// 同步账户账号日流水
						fundDailyService.getFundDaily(advertiserIds.getId(), startDate, today, curPage, curPageSize);
						// 暂停一秒
						Thread.sleep(1000);
						// 同步广告主资质信息
						qualificationService.getQualification(advertiserIds.getId());
						// 同步广告主投放资质信息
						deliverService.getQualificationDeliver(advertiserIds.getId());
					} catch (Exception e) {
						e.printStackTrace();
					}
					String tip = "共{}条数据，当前是第{}条数据";
					System.out.println(StringUtils.format(tip, total, beginIndex + j));
				}
			});
		}
	}

	/**
	 * 同步代理商下属所有广告主信息、账户资金数据等
	 *
	 * @param advertiserId 代理商广告主id
	 * @throws Exception
	 */
	@Override
	public void syncBaseInfo(String advertiserId) throws Exception {
		if (StringUtils.isEmpty(advertiserId))
			return;

		AdvertiserIds base = new AdvertiserIds();
		base.setPId(Long.valueOf(advertiserId));
		List<AdvertiserIds> advertiserIdsList = advertiserIdsMapper.selectAdvertiserIdsList(base);

		double total = advertiserIdsList.size();
		int pageSize = 1000;
		int totalPage = (int) Math.ceil(total / pageSize);

		for (int i = 0; i < totalPage; i++) {
			int beginIndex = i * pageSize;
			int endIndex = (int) Math.min((i + 1) * pageSize, total);
			Executors.newFixedThreadPool(totalPage).execute(() -> {
				List<AdvertiserIds> advertiserIds = advertiserIdsList.subList(beginIndex, endIndex);
				int step = 20;
				long[] ids = new long[20];
				for (int j = 0; j < advertiserIds.size(); j += step) {
					for (int m = 0; m < step; m++) {
						ids[m] = advertiserIds.get(j + m).getId();
					}
					try {
						// 同步广告主详情信息
						advertiserService.getAdvertiserDetails(ids);
						Thread.sleep(1000);
						// 同步广告主日预算数据
						budgetService.getBudget(ids);
						Thread.sleep(1000);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
			});
		}

		// 同步未成功或同步失败的广告主信息
		advertiserService.retryAdvertisers();
	}
}
